package com.dcy.daily.common.dataSource;

import com.alibaba.druid.pool.DruidDataSource;
import com.dcy.daily.common.constant.Constants;
import com.dcy.daily.common.dataSource.properties.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * 多个数据源配置
 * @author duanchunyu
 * @version 1.0.0
 * @createTime 2021年05月28日 16:14:00
 */
@Configuration
public class DataSourceConfig {

    @Bean(name = "originalDataSource")
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource originalDataSource(){
        return new DruidDataSource();
    }

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.secondary")
    public DataSourceProperties secondDataSourceProperties(){
        return new DataSourceProperties();
    }

    @Bean
    @Primary
    public DataSource dynamicDataSource(DataSource originalDataSource,
                                        DataSourceProperties secondDataSourceProperties){
        Map<Object, Object> targetDataSourcesMap = new HashMap<>();
        DataSource secondaryDataSource = secondDataSourceProperties.setDruidDataSource(originalDataSource);
        targetDataSourcesMap.put(Constants.DATA_SOURCE_TYPE.PRIMARY,originalDataSource);
        targetDataSourcesMap.put(Constants.DATA_SOURCE_TYPE.SECONDARY,secondaryDataSource);
        DynamicDataSource dynamicDataSource = new DynamicDataSource(originalDataSource,targetDataSourcesMap);
        return dynamicDataSource;
    }
}
